﻿using System;

namespace XUtility
{
    #region Double 类型 扩展方法

    public static class DoubleEx
    {
        /// <summary>
        /// 返回Int类型
        /// </summary>
        /// <param name="i">输入数据型</param>
        /// <returns>Int类型</returns>
        public static Int32 ToDouble(this Double? i)
        {
            if (i.HasValue)
            {
                return i.Value.ToInt32();
            }
            return 0;
        }

        /// <summary>
        /// 返回Int类型
        /// </summary>
        /// <param name="i">输入数据型</param>
        /// <returns>Int类型</returns>
        public static Int32 ToInt32(this Double i)
        {
            return (Int32)i;
        }

        #region 返回Decimal类型
        /// <summary>
        /// 返回Decimal类型
        /// </summary>
        /// <param name="d">Double值</param>
        /// <returns>Decimal类型</returns>
        public static Decimal ToDecimal(this Double d)
        {
            return d.ToDecimal(0M);
        }
        /// <summary>
        /// 返回Decimal类型
        /// </summary>
        /// <param name="d">Double值</param>
        /// <param name="v">默认值</param>
        /// <returns>Decimal类型</returns>
        public static Decimal ToDecimal(this Double d, Decimal v)
        {
            Decimal result;
            if(!Decimal.TryParse(d.ToString(), out result))
            {
                result = v;
            }

            return result;
        }
        #endregion

        #region 返回百份比字符串
        /// <summary>
        /// 返回百份比字符串类型
        /// </summary>
        /// <param name="d"></param>
        /// <returns></returns>
        public static String ToPerCent(this Double d)
        {
            return (d * 100).ToString();
        }
        #endregion

        #region 四舍五入
        /// <summary>
        /// 四舍五入
        /// </summary>
        /// <param name="d"></param>
        /// <returns></returns>
        public static Int32 Round(this Double d)
        {
            Int32 result = 0;
            Int32 i = (Int32)d;
            if(d - i >= 0.5)
                result = i + 1;
            else
                result = i;

            return result;
        }
        #endregion
    }
    #endregion
}
